package com.aura.blog.service.impl;

import com.aura.blog.dto.request.UserLoginRequest;
import com.aura.blog.dto.response.UserInfoResponse;
import com.aura.blog.dto.response.UserLoginResponse;
import com.aura.blog.entity.BlogInfo;
import com.aura.blog.entity.UserInfo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.aura.blog.common.constant.Constants;
import com.aura.blog.common.exception.BlogException;
import com.aura.blog.common.util.BeanTransUtils;
import com.aura.blog.common.util.JwtUtils;
import com.aura.blog.common.util.Md5Utils;
import com.aura.blog.mapper.UserInfoMapper;
import com.aura.blog.service.BlogService;
import com.aura.blog.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl implements UserService {
    @Resource(name = "userInfoMapper")
    private UserInfoMapper userInfoMapper;

    @Resource(name = "blogServiceImpl")
    private BlogService blogService;

    @Override
    public UserLoginResponse check(UserLoginRequest loginRequest) {
        /**
         * 1. 判断密码是否正确
         * 2. 如果正确, 返回token
         */
        UserInfo userInfo = selectUserInfoByName(loginRequest.getUserName());
        if (userInfo ==null){
            //用户不存在
            throw new BlogException("用户不存在");
        }
//        if (!loginRequest.getPassword().equals(userInfo.getPassword())){
//            //密码不正确
//            throw new BlogException("密码不正确");
//        }
        if (!Md5Utils.verify(loginRequest.getPassword(), userInfo.getPassword())){
            //密码不正确
            throw new BlogException("密码不正确");
        }
        //密码正确
        Map<String, Object> map = new HashMap<>();
        map.put("id", userInfo.getId());
        map.put("name", userInfo.getUserName());
        String token = JwtUtils.genJwt(map);
        return new UserLoginResponse(userInfo.getId(), token);
    }

    @Override
    public UserInfoResponse getUserInfo(Integer userId) {
        return BeanTransUtils.transUser(selectUserInfoById(userId));
    }

    @Override
    public UserInfoResponse getAuthorInfo(Integer blogId) {
        BlogInfo blogInfo = blogService.getBlogInfo(blogId);
        if (blogInfo ==null){
            throw new BlogException("博客不存在");
        }
        return BeanTransUtils.transUser(selectUserInfoById(blogInfo.getUserId()));
    }
    
    @Override
    public List<UserInfoResponse> getAllUsers() {
        List<UserInfo> userInfos = userInfoMapper.selectList(
                new LambdaQueryWrapper<UserInfo>().eq(UserInfo::getDeleteFlag, Constants.NOT_DELETE)
                        .orderByDesc(UserInfo::getUpdateTime)
        );
        return userInfos.stream().map(BeanTransUtils::transUser)
                .collect(Collectors.toList());
    }
    
    @Override
    public UserInfoResponse getUserDetail(Integer userId) {
        return BeanTransUtils.transUser(selectUserInfoById(userId));
    }
    
    @Override
    public Boolean createUser(UserInfo userInfo) {
        // 对密码进行MD5加密
        if (userInfo.getPassword() != null) {
            userInfo.setPassword(Md5Utils.enrypt(userInfo.getPassword()));
        }
        
        // 设置创建时间和更新时间
        userInfo.setCreateTime(new Date());
        userInfo.setUpdateTime(new Date());
        userInfo.setDeleteFlag(String.valueOf(Constants.NOT_DELETE));
        
        try {
            userInfoMapper.insert(userInfo);
            return true;
        } catch (Exception e) {
            throw new BlogException("用户创建失败");
        }
    }
    
    @Override
    public Boolean updateUser(UserInfo userInfo) {
        // 设置更新时间
        userInfo.setUpdateTime(new Date());
        
        try {
            int i = userInfoMapper.updateById(userInfo);
            return i == 1;
        } catch (Exception e) {
            throw new BlogException("用户更新失败");
        }
    }
    
    @Override
    public Boolean deleteUser(Integer userId) {
        UserInfo userInfo = new UserInfo();
        userInfo.setId(userId);
        userInfo.setDeleteFlag(String.valueOf(Constants.IS_DELETE));
        userInfo.setUpdateTime(new Date());
        
        try {
            int i = userInfoMapper.updateById(userInfo);
            return i == 1;
        } catch (Exception e) {
            throw new BlogException("用户删除失败");
        }
    }

    public UserInfo selectUserInfoByName(String userName){
        return userInfoMapper.selectOne(
                new LambdaQueryWrapper<UserInfo>()
                        .eq(UserInfo::getUserName, userName)
                        .eq(UserInfo::getDeleteFlag, Constants.NOT_DELETE)
        );
    }

    public UserInfo selectUserInfoById(Integer userId){
        return userInfoMapper.selectOne(
                new LambdaQueryWrapper<UserInfo>()
                        .eq(UserInfo::getId, userId)
                        .eq(UserInfo::getDeleteFlag, Constants.NOT_DELETE)
        );
    }
}